package com.gsafety.wellsfort.controller.index;

import com.gsafety.wellsfort.common.enums.RedisPrefixEnum;
import com.gsafety.wellsfort.common.util.ApiResponse;
import com.gsafety.wellsfort.common.util.DateUtil;
import com.gsafety.wellsfort.common.util.StringUtil;
import com.gsafety.wellsfort.config.CacheManager;
import com.gsafety.wellsfort.dao.course.*;
import com.gsafety.wellsfort.domain.model.course.LearningProgress;
import com.gsafety.wellsfort.domain.model.course.StudentExam;
import com.gsafety.wellsfort.domain.model.course.StudentWork;
import com.gsafety.wellsfort.domain.model.organization.School;
import com.gsafety.wellsfort.domain.model.organization.Student;
import com.gsafety.wellsfort.domain.vo.*;
import com.gsafety.wellsfort.domain.vo.security.IndexCourseVO;
import com.gsafety.wellsfort.service.course.CourseService;
import com.gsafety.wellsfort.service.knowledge.ExamService;
import com.gsafety.wellsfort.service.knowledge.WorkService;
import com.gsafety.wellsfort.service.organization.IClassService;
import com.gsafety.wellsfort.service.organization.ISchoolService;
import com.gsafety.wellsfort.service.organization.IStudentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.*;

@Api(value = "首页统计", description = "首页统计")
@RestController
@Slf4j
@RequestMapping("/api/index")
public class IndexController {

    @Autowired
    private CacheManager cacheManager;
    @Autowired
    private ISchoolService schoolService;
    @Autowired
    private IClassService classService;

    @Autowired
    private IStudentService studentService;

    @Autowired
    private CourseService courseService;

    @Autowired
    private WorkService workService;

    @Autowired
    private ExamService examService;

    @Autowired
    private LessonPeriodDAO lessonPeriodDAO;
    @Autowired
    private StudentWorkDAO studentWorkDAO;
    @Autowired
    private StudentExamDAO studentExamDAO;
    @Autowired
    private LearningProgressDAO learningProgressDAO;


    @ApiOperation(value = "系统基础信息:包含入驻学校、安全教书等..")
    @PostMapping("/baseInfo")
    public ApiResponse<BaseInfoVO> baseInfo() {
        Integer schoolCount = schoolService.count();
        Integer classCount = classService.count();
        Integer studentCount = studentService.count();
        Integer courseCount = courseService.count();
        long visitCount = cacheManager.get(RedisPrefixEnum.VISIT_SYSTEM_COUNT.getPrefix()) == null ? 0L : Long.parseLong(cacheManager.get(RedisPrefixEnum.VISIT_SYSTEM_COUNT.getPrefix()));
        Integer finishWorkCount = workService.finishWorkCount();
        Integer finishExamCount = examService.finishExamCount();
        Integer finishCount = lessonPeriodDAO.finishCount();
        BaseInfoVO baseInfoVO = BaseInfoVO.builder().schoolNum(schoolCount).classNum(classCount).studentNum(studentCount).
                courseNum(courseCount).visitNum(visitCount).courseStudyNum(finishCount).completeExamNum(finishExamCount).completeWorkNum(finishWorkCount).build();
        return ApiResponse.success(baseInfoVO);
    }

    @ApiOperation(value = "新增课程")
    @PostMapping("/addCourseQuantity")
    public ApiResponse<List<AddCourseQuantityVO>> addCourseQuantity() {
        return ApiResponse.success(courseService.getIncrCourse());
    }

    @ApiOperation(value = "学习人数")
    @PostMapping("/getStudyQuantity")
    public ApiResponse<StudyQuantityVO> getStudyQuantity() {
        StudyQuantityVO studyQuantityVO = new StudyQuantityVO();
        Date date = new Date();
        for (int i = 6; i >= 0; i--) {
            DateVO dateVO = DateUtil.getDateRange(date, -i);
            studyQuantityVO.addDate(dateVO.getDesc());
            String key = "course_detail_count_" + new SimpleDateFormat("yyyyMMdd").format(dateVO.getStart());
            String value = cacheManager.get(key);
            studyQuantityVO.addCourseStudy(StringUtils.isEmpty(value) ? 0 : Integer.parseInt(value));
            studyQuantityVO.addWorkStudy(studentWorkDAO.countStartTimeByRange(dateVO.getStart(), dateVO.getEnd()));
            studyQuantityVO.addExamStudy(studentExamDAO.countStartTimeByRange(dateVO.getStart(), dateVO.getEnd()));
        }
        return ApiResponse.success(studyQuantityVO);
    }


    @ApiOperation(value = "实时学习动态")
    @PostMapping("/getStudying")
    public ApiResponse<StudyingDataVO> getStudying() {
        StudyingDataVO dataVO = new StudyingDataVO();
        /**
         * 课程正在学习统计:(1)根据app上传学习时长更新时间,采用时间差范围统计,学习进度表更新时间+15分钟>当前时间,表示他正在学习该课程
         *  (2)作业，考试, 答题时间<当前时间,且没有完成时间则认为正在做题
         */
        Date startDate = DateUtil.getPrevMinute(-1 * 15);
        Date endDate = new Date();
        List<LearningProgress> learningProgressList = learningProgressDAO.selectByRangeDate(startDate, endDate);
        if (learningProgressList != null && learningProgressList.size() > 0) {
            for (LearningProgress learningProgress : learningProgressList) {
                if (learningProgress != null) {
                    IndexCourseVO courseVO = new IndexCourseVO();
                    ApiResponse<CourseDetailVO> apiResponse = courseService.getCourseDetail(learningProgress.getCourseId());
                    if (apiResponse != null && apiResponse.getData() != null) {
                        courseVO.setName(apiResponse.getData().getName());
                    }
                    Student student = studentService.get(learningProgress.getStudentId());
                    if (student != null) {
                        School school = schoolService.get(student.getSchoolId());
                        courseVO.setUserName(student.getName());
                        if (school != null) {
                            courseVO.setSchoolName(school.getName());
                        }
                    }
                    dataVO.addCourse(courseVO);
                }
            }
        }
        //统计正在做作业学生
        List<StudentWork> studentWorkList = studentWorkDAO.getDoingWork();
        if (studentWorkList != null && studentWorkList.size() > 0) {
            for (StudentWork studentWork : studentWorkList) {
                if (studentWork != null) {
                    IndexCourseVO courseVO = new IndexCourseVO();
                    ApiResponse<WorkVO> apiResponse = workService.getWork(studentWork.getWorkId());
                    if (apiResponse != null && apiResponse.getData() != null) {
                        courseVO.setName(apiResponse.getData().getWorkTitle());
                    }
                    Student student = studentService.get(studentWork.getStudentId());
                    if (student != null) {
                        School school = schoolService.get(student.getSchoolId());
                        courseVO.setUserName(student.getName());
                        if (school != null) {
                            courseVO.setSchoolName(school.getName());
                        }
                    }
                    if (StringUtils.isNoneEmpty(courseVO.getName())) {
                        dataVO.addWork(courseVO);
                    }
                }
            }
        }

        //统计正在做试卷学生
        List<StudentExam> studentExamList = studentExamDAO.getDoingWork();
        if (studentExamList != null && studentExamList.size() > 0) {
            for (StudentExam studentExam : studentExamList) {
                if (studentExam != null) {
                    IndexCourseVO courseVO = new IndexCourseVO();
                    ApiResponse<ExamVO> apiResponse = examService.getExam(studentExam.getExamId());
                    if (apiResponse != null && apiResponse.getData() != null) {
                        courseVO.setName(apiResponse.getData().getExamTitle());
                    }
                    Student student = studentService.get(studentExam.getStudentId());
                    if (student != null) {
                        School school = schoolService.get(student.getSchoolId());
                        courseVO.setUserName(student.getName());
                        if (school != null) {
                            courseVO.setSchoolName(school.getName());
                        }
                    }
                    if (StringUtils.isNoneEmpty(courseVO.getName())) {
                        dataVO.addExam(courseVO);
                    }
                }
            }
        }
        return ApiResponse.success(dataVO);
    }


    @ApiOperation(value = "热门课程排行")
    @PostMapping("/hotCourse")
    public ApiResponse<List<String>> hotCourse() {
        List<String> list = new ArrayList<>();
        Map<String, Integer> map = cacheManager.getHash(RedisPrefixEnum.COURSE_VISIT_COUNT_PREFIX.getPrefix());
        if (map != null && map.size() > 0) {
            for (Map.Entry<String, Integer> entry : map.entrySet()) {
                if (StringUtils.isNotEmpty(entry.getKey())) {
                    ApiResponse<CourseDetailVO> apiResponse = courseService.getCourseDetail(Integer.parseInt(entry.getKey()));
                    if (apiResponse != null && apiResponse.getData() != null) {
                        if (StringUtils.isNoneEmpty(apiResponse.getData().getName())) {
                            list.add(apiResponse.getData().getName());
                        }
                    }
                }
            }
        }
        return ApiResponse.success(list, list.size());
    }

    @ApiOperation(value = "学校地图,返回学校地址")
    @PostMapping("/schoolMap")
    public ApiResponse<List<School>> schoolMap() {
        return schoolService.list();
    }

    @ApiOperation(value = "活跃用户")
    @PostMapping("/activeUser")
    public ApiResponse<ActiveUserVO> activeUser() {
        ActiveUserVO activeUserVO = new ActiveUserVO();
        Date date = new Date();
        for (int i = 6; i >= 0; i--) {
            DateVO dateVO = DateUtil.getDateRange(date, -i);
            activeUserVO.addDate(dateVO.getDesc());
            String key = "active_student_count_" + new SimpleDateFormat("yyyyMMdd").format(dateVO.getStart());
            List<String> list = cacheManager.getList(key);
            activeUserVO.addActiveCount(list == null ? 0 : list.size());
            activeUserVO.addCount(studentService.countStartTimeByRange(dateVO.getStart(), dateVO.getEnd()));
        }
        return ApiResponse.success(activeUserVO);
    }

    @ApiOperation(value = "安意能统计")
    @PostMapping("/ayineng")
    public ApiResponse<AnYiNengIndexVO> ayineng() {
        AnYiNengIndexVO anYiNengIndexVO = new AnYiNengIndexVO();
        anYiNengIndexVO.setAbility(0.5d);
        anYiNengIndexVO.setAware(0.2d);
        anYiNengIndexVO.setIdentity(0.1d);
        anYiNengIndexVO.setHistory(0.1d);
        anYiNengIndexVO.setAware(0.1d);
        return ApiResponse.success(anYiNengIndexVO);
    }
}
